package com.example.demo.websocket;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@ServerEndpoint("/websocket/{login_id}")
public class WebSocket {
	
	private Session session;
	
	private String login_id;

    private static ConcurrentHashMap<String, WebSocket> webSocketMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session,@PathParam(value="login_id")String login_id) {
        this.session = session;
        this.login_id  =login_id;
        webSocketMap.put(login_id, this);
        log.info("【websocket消息】有新的连接,连接用户为{}, 总数:{}",this.login_id ,webSocketMap.size());
    }

    @OnClose
    public void onClose() {
    	webSocketMap.remove(this.login_id);
        log.info("【websocket消息】用户{}连接断开, 总数:{}", this.login_id, webSocketMap.size());
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("【websocket消息】收到客户端{}发来的消息:{}",this.login_id ,message);
    }
    
    @OnError
    public void onError(Throwable e) {
    	log.error("【websocket消息】连接失败",e);
    }

    public void sendMessage(String message) throws IOException {
    	this.session.getBasicRemote().sendText(message);
    }
}
